package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.taobao.top.schema.exception.TopSchemaException;
import com.taobao.top.schema.factory.SchemaReader;
import com.taobao.top.schema.field.InputField;
import com.taobao.top.schema.rule.Rule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author：LXY
 * @DATE：2025-09-14 12:49
 * @Description：获取产品信息 判断是否可以发布商品
 */
@Component
@Slf4j
public class Jh60GetProductInfoHandler implements PriorityHandler {
    @Autowired
    private CallTaoApiService callTaoApiService;
    @Override
    public int getPriority() {
        return 60;
    }

    @Override
    public boolean handle(ProcessContext<JSONObject> request) throws IOException {
        JSONObject data = request.getData();
        Long productId = data.getLong("productId");
        if (productId == null) {
            request.setErrorInfo("productId(产品ID)为空");
            throw new RuntimeException("productId(产品ID)为空");
        }
        JhTmAccount jhTmAccount = data.getObject("tmAccount", JhTmAccount.class);
        String productSchema = callTaoApiService.getProductSchema(jhTmAccount, productId);
        Map result = null;
        try {
            result = SchemaReader.readXmlForMap(productSchema);
        } catch (TopSchemaException e) {
            request.setErrorInfo("解析商品Schema失败:"+e.getMessage());
            throw new RuntimeException(e);
        }
        InputField canPublishItem = (InputField) result.get("can_publish_item");
        if (canPublishItem != null){
            List<Rule> rules = canPublishItem.getRules();
            for (Rule rule : rules) {
                if (rule.getName().equals("tipRule") && rule.getValue().equals("可以发布商品")){
                    return true;
                }
            }
        }
        request.setErrorInfo("商品不可以发布");
        throw new RuntimeException("商品不可以发布");
    }
}
